package cn.itcast.service;

import cn.itcast.interfaces.UserService;
import cn.itcast.mapper.PermissionMapper;
import cn.itcast.mapper.RoleMapper;
import cn.itcast.mapper.UserMapper;
import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Set;

/**
 * @author: peterChen
 * @date: 2019/8/16 16:06
 * @description: TODO
 * @version: 1.0
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;


    /**
     * 根据用户名获取用户角色及权限信息
     * @param userName
     * @return
     */
    @Override
    public User findByUsername(String userName) {
        //根据username获取user信息
        User user = userMapper.findUserByUserName(userName);
        if(ObjectUtils.isEmpty(user)){
            return null;
        }
        //根据user的id获取role的信息，并填充进user的成员变量
        Set<Role> roles = roleMapper.findRolesByUserId(user.getId());
        if(!CollectionUtils.isEmpty(roles) && roles.size()>0) {
            for (Role role : roles) {
                //根据role的id获取权限列表
                Set<Permission> permissions = permissionMapper.findPermissionsByRoleId(role.getId());
                if(!CollectionUtils.isEmpty(permissions) && permissions.size() > 0) {
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }
        return user;
    }
}
